package com.kevin.jdbc.daoUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class ConnectionHandler implements InvocationHandler {

	private Connection realConnection;
	private Connection wrapedConnection;

	public Connection getWrapedConnection() {
		return wrapedConnection;
	}

	public ConnectionHandler(Connection conn) {
		this.realConnection = conn;
		this.wrapedConnection = (Connection) Proxy.newProxyInstance(
				Connection.class.getClassLoader(),
				new Class[] { Connection.class }, this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		if ("close".equals(method.getName())) {
			CommonDataSource.freeConnection(this.realConnection);

			return null;
		} else {
			return method.invoke(this.realConnection, args);
		}
	}
}
